package cn.edu.pku.ss.situationperceiver;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DBAdapter {
	private static final String DB_NAME = "sra.db";
	private static final String DB_TABLE = "sra";
	private static final int DB_VERSION = 1;
	
	private static final String ID = "id";
	private static final String TRIGGER = "triggerID";
	private static final String RESULT = "resultID";
	private static final String INTER = "intermediateID";
	
	private SQLiteDatabase db;
	private final Context context;
	private DBOpenHelper dbOpenHelper;
	
	private static class DBOpenHelper extends SQLiteOpenHelper{

		private static final String DB_CREATE = "create table " + DB_TABLE + " (" + ID
				+ " integer primary key autoincrement, " + TRIGGER + " text not null, "
				+ RESULT + " text not null, " + INTER + " text not null);";
				
		public DBOpenHelper(Context context, String name, CursorFactory factory, int version) {
			super(context, name, factory, version);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			db.execSQL(DB_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
			onCreate(db);
		}
		
	}
	
	public DBAdapter(Context _context){
		context = _context;
	}
	
	public void open() throws SQLiteException{
		dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);
		try{
			db = dbOpenHelper.getWritableDatabase();
		}catch (SQLiteException ex) {
			db = dbOpenHelper.getReadableDatabase();
		}
	}
	
	public void close(){
		if(db != null)
		{
			db.close();
			db = null;
		}
	}
	
	public long insert(ReasoningRecord rr){
		ContentValues newValues = new ContentValues();
		newValues.put(TRIGGER, rr.tiggerID);
		newValues.put(RESULT, rr.resultID);
		newValues.put(INTER, rr.intermediateID);
		return db.insert(DB_TABLE, null, newValues);
	}
}
